<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\api\model\OrderGoods;
use app\api\model\ShopGoods;
use app\common\controller\Api;
use think\Db;

/**
 * pay-支付回调
 * @ApiWeigh (1)
 */
class Notify extends Api {
	// 无需登录的接口,*表示全部
	protected $noNeedLogin = ['*'];
	// 无需鉴权的接口,*表示全部
	protected $noNeedRight = ['*'];

	/**
	 * 微信支付回调
	 */
	public function service() {
		$type = $this->request->param( 'type' );
		$pay  = Service::checkNotify( $type );
		if ( !$pay ) {
			return '签名错误';
		}
		$time = time();
		$data = $pay->verify();
		$data = json_decode( $data, true );
		//输出返回的参数
//		file_put_contents( 'xue.txt', print_r( $data, true ), FILE_APPEND );
		$orderModel = new \app\api\model\Order();
		$orderGoodsModel = new OrderGoods();
		$shopGoodsModel = new ShopGoods();
		//查询订单信息
		$order_info = $orderModel->where('order_no',$data['out_trade_no'] )->find();
		if ( $data['return_code'] == 'SUCCESS' ) {

			if ( $data['result_code'] == 'SUCCESS' ) {
				$update_data = [
					'transaction_id' => $data['transaction_id'],
					'order_status'   => 2,
					'pay_type'       => 1,
					'pay_time'       => $time,
					'is_pay'         => 1,
					'updatetime'     => $time,
				];
				//更新订单信息
				$orderModel->where( 'order_no', $data['out_trade_no'] )->update( $update_data );
				//查询订单对应商品规格的 商品ids
				$goods_ids = $orderGoodsModel->where('order_id',$order_info['id'])->column('goods_id');
				//支付成功减库存
				foreach ($goods_ids as $v){
					$order_goods_info = $orderGoodsModel->where('order_id',$order_info['id'])->where('goods_id',$v)->find();
					$shopGoodsModel->where('id',$v)->setDec('stock_num',$order_goods_info['total_num']);
				}
			}
		}
		return $pay->success()->send();
	}

	/**
	 * 微信支付测试退款接口(内部)
	 */
	public function refund() {
		$app    = WechatPayment::getInstance();
		$result = $app->refund->byTransactionId( '4200001369202204111206992152', 'refund1649646625657117835486', 50, 50, [
			// 可在此处传入其他参数，详细参数见微信支付文档
			'refund_desc' => '商品已售完',
		] );
	}

}
